package com.shioirikukuri.mq;

import com.shioirikukuri.common.exception.BusinessException;
import com.shioirikukuri.common.web.Result;
import com.shioirikukuri.service.IOrderInfoService;
import com.shioirikukuri.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(topic = MQConstant.ORDER_CREATE_TOPIC,consumerGroup = "orderCreateGroup")
public class OrderCreateMessageListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage message) {
        //通过WebSocket通知客户端
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setToken(message.getToken());

        try {
            //成功时发送订单码，订单号
            String orderNo = orderInfoService.createSeckillOrder(message.getSeckillId(),message.getUserPhone());
            orderMQResult.setCode(Result.SUCCESS_CODE);
            orderMQResult.setOrderNo(orderNo);
            //成功后发送延时消息
            Message<String> delayMsg = MessageBuilder.withPayload(orderNo).build();
            rocketMQTemplate.syncSend(
                    MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
                    delayMsg,
                    MQConstant.MESSAGE_SEND_TIMEOUT
            );

            System.out.println("Websocket通知:秒杀成功");
        }catch (BusinessException e){
            //秒杀失败结果通知
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            System.out.println("秒杀失败"+e.getMessage());
        }
        rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC,orderMQResult);



    }
}
